<template>
  <div class="page-container">
    <div class="page-header">
      <h2>用户管理</h2>
      <p>管理系统用户信息和状态</p>
    </div>
    
    <el-card class="action-card">
      <div class="action-container">
        <el-button type="primary" @click="showAddDialog">
          <el-icon><Plus /></el-icon>
          添加用户
        </el-button>
      </div>
    </el-card>
    
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="users"
        style="width: 100%"
        border
      >
        <el-table-column
          prop="id"
          label="ID"
          width="80"
        />
        <el-table-column
          prop="username"
          label="用户名"
          min-width="120"
        />
        <el-table-column
          prop="fullName"
          label="姓名"
          min-width="120"
        />
        <el-table-column
          prop="email"
          label="邮箱"
          min-width="180"
        />
        <el-table-column
          prop="role"
          label="角色"
          width="100"
        >
          <template #default="scope">
            <el-tag :type="scope.row.role === 'ADMIN' ? 'danger' : 'success'">
              {{ scope.row.role === 'ADMIN' ? '管理员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="enabled"
          label="状态"
          width="100"
        >
          <template #default="scope">
            <el-tag :type="scope.row.enabled ? 'success' : 'info'">
              {{ scope.row.enabled ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="180"
          fixed="right"
        >
          <template #default="scope">
            <!-- 不允许管理员修改其他管理员的信息 -->
            <div v-if="scope.row.role !== 'ADMIN' || scope.row.id === currentUserId">
              <el-button
                type="primary"
                size="small"
                circle
                @click="handleEdit(scope.row)"
              >
                <el-icon><Edit /></el-icon>
              </el-button>
              <el-button
                :type="scope.row.enabled ? 'warning' : 'success'"
                size="small"
                circle
                @click="handleToggleStatus(scope.row)"
              >
                <el-icon>
                  <component :is="scope.row.enabled ? 'Lock' : 'Unlock'" />
                </el-icon>
              </el-button>
              <!-- 不允许删除自己或管理员账号 -->
              <el-button
                v-if="scope.row.role !== 'ADMIN' && scope.row.id !== currentUserId"
                type="danger"
                size="small"
                circle
                @click="handleDelete(scope.row)"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
            <div v-else>
              <el-tag type="info">无权操作</el-tag>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 编辑用户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑用户信息' : '添加用户'"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="输入用户名" :disabled="isEdit" />
        </el-form-item>
        
        <el-form-item v-if="!isEdit" label="密码" prop="password">
          <el-input v-model="form.password" type="password" placeholder="输入密码" show-password />
        </el-form-item>
        
        <el-form-item label="姓名" prop="fullName">
          <el-input v-model="form.fullName" placeholder="输入用户姓名" />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="输入用户邮箱" />
        </el-form-item>
        
        <el-form-item label="手机" prop="phone">
          <el-input v-model="form.phone" placeholder="输入手机号码" />
        </el-form-item>
        
        <el-form-item label="性别" prop="gender">
          <el-select v-model="form.gender" placeholder="选择性别" style="width: 100%">
            <el-option label="男" value="MALE" />
            <el-option label="女" value="FEMALE" />
            <el-option label="其他" value="OTHER" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="出生日期" prop="birthDate">
          <el-date-picker
            v-model="form.birthDate"
            type="date"
            placeholder="选择出生日期"
            style="width: 100%"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        
        <el-form-item label="角色" prop="role">
          <el-select v-model="form.role" placeholder="选择用户角色" style="width: 100%">
            <el-option label="普通用户" value="USER" />
            <el-option label="管理员" value="ADMIN" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="状态" prop="enabled">
          <el-switch
            v-model="form.enabled"
            :active-text="form.enabled ? '启用' : '禁用'"
            :inactive-text="form.enabled ? '启用' : '禁用'"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :disabled="isEdit && form.role === 'ADMIN' && currentUserId !== currentUser?.id"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitting">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUserList, adminUpdateUser, deleteUser, createUser } from '@/api/user'
import { Plus, Edit, Delete, Lock, Unlock } from '@element-plus/icons-vue'

const currentUserId = computed(() => parseInt(localStorage.getItem('userId') || '0'))

const loading = ref(false)
const users = ref([])
const dialogVisible = ref(false)
const submitting = ref(false)
const formRef = ref(null)
const isEdit = ref(false)

// 当前编辑的用户
const currentUser = ref(null)

// 表单数据
const form = ref({
  username: '',
  password: '',
  fullName: '',
  email: '',
  phone: '',
  gender: null,
  birthDate: null,
  role: 'USER',
  enabled: true
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在3到20个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur', validator: (rule, value, callback) => {
      if (isEdit.value) {
        callback()
      } else if (!value || value.length < 6) {
        callback(new Error('密码长度不能少于6个字符'))
      } else {
        callback()
      }
    }}
  ],
  fullName: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在2到50个字符之间', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择用户角色', trigger: 'change' }
  ]
}

// 获取所有用户
const fetchUsers = async () => {
  loading.value = true
  
  try {
    users.value = await getUserList()
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 显示添加对话框
const showAddDialog = () => {
  isEdit.value = false
  currentUser.value = null
  form.value = {
    username: '',
    password: '',
    fullName: '',
    email: '',
    phone: '',
    gender: null,
    birthDate: null,
    role: 'USER',
    enabled: true
  }
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = (row) => {
  isEdit.value = true
  currentUser.value = row
  form.value = {
    username: row.username,
    password: '', // 编辑时不显示密码
    fullName: row.fullName || '',
    email: row.email || '',
    phone: row.phone || '',
    gender: row.gender || null,
    birthDate: row.birthDate ? row.birthDate.substring(0, 10) : null,
    role: row.role || 'USER',
    enabled: row.enabled
  }
  dialogVisible.value = true
}

// 切换用户状态
const handleToggleStatus = (row) => {
  // 不允许禁用自己的账号
  if (row.id === currentUserId.value) {
    ElMessage.warning('不能禁用自己的账号')
    return
  }
  
  // 不允许操作其他管理员账号
  if (row.role === 'ADMIN') {
    ElMessage.warning('不能修改其他管理员的状态')
    return
  }
  
  const statusText = row.enabled ? '禁用' : '启用'
  
  ElMessageBox.confirm(
    `确定要${statusText}该用户吗？`,
    `${statusText}用户`,
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await adminUpdateUser(row.id, {
        enabled: !row.enabled
      })
      ElMessage.success(`用户${statusText}成功`)
      fetchUsers()
    } catch (error) {
      console.error(`${statusText}用户失败:`, error)
      ElMessage.error(error.response?.data?.message || `${statusText}用户失败`)
    }
  }).catch(() => {})
}

// 处理删除
const handleDelete = (row) => {
  // 不允许删除自己
  if (row.id === currentUserId.value) {
    ElMessage.warning('不能删除自己的账号')
    return
  }
  
  // 不允许删除管理员
  if (row.role === 'ADMIN') {
    ElMessage.warning('不能删除管理员账号')
    return
  }
  
  ElMessageBox.confirm(
    '确定要删除该用户吗？此操作不可恢复。',
    '删除用户',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteUser(row.id)
      ElMessage.success('用户删除成功')
      fetchUsers()
    } catch (error) {
      console.error('删除用户失败:', error)
      ElMessage.error(error.response?.data?.message || '删除用户失败')
    }
  }).catch(() => {})
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    
    submitting.value = true
    
    try {
      // 不允许修改自己的启用状态
      if (isEdit.value && currentUser.value.id === currentUserId.value && !form.value.enabled) {
        ElMessage.warning('不能禁用自己的账号')
        form.value.enabled = true
        submitting.value = false
        return
      }
      
      // 不允许修改其他管理员的状态
      if (isEdit.value && currentUser.value.role === 'ADMIN' && 
          currentUser.value.id !== currentUserId.value) {
        // 确保不修改管理员的状态
        form.value.enabled = currentUser.value.enabled
      }
      
      const submitData = {
        username: form.value.username,
        fullName: form.value.fullName,
        email: form.value.email,
        phone: form.value.phone,
        gender: form.value.gender,
        birthDate: form.value.birthDate,
        role: form.value.role,
        enabled: form.value.enabled
      }
      
      // 添加密码（仅在创建用户时）
      if (!isEdit.value) {
        submitData.password = form.value.password
      }
      
      if (isEdit.value) {
        await adminUpdateUser(currentUser.value.id, submitData)
        ElMessage.success('更新成功')
      } else {
        // 创建用户API
        await createUser(submitData)
        ElMessage.success('创建成功')
      }
      
      dialogVisible.value = false
      fetchUsers()
    } catch (error) {
      console.error(isEdit.value ? '更新用户失败:' : '创建用户失败:', error)
      ElMessage.error(error.response?.data?.message || (isEdit.value ? '更新用户失败' : '创建用户失败'))
    } finally {
      submitting.value = false
    }
  })
}

onMounted(() => {
  fetchUsers()
})
</script>

<style scoped>
.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 10px 0;
  font-weight: 500;
}

.page-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.table-card {
  margin-bottom: 20px;
}
</style> 